'use strict'

$(function () {
    // 根据id获取值
    let id = location.search.split('?')[1];
    if (id) {
        $.get('http://localhost:8000/product', data => {
            let newdata = data.filter(item => {
                return item.id == id
            })
            $('[name=id]').val(newdata[0].id);
            $('[name=name]').val(newdata[0].name);
            $('[name=price]').val(newdata[0].price);
            $('[name=supplier]').val(newdata[0].supplier);
        })
    }
})

function save() {
    let obj = {
        id: $('[name=id]').val(),
        name: $('[name=name]').val(),
        price: $('[name=price]').val(),
        supplier: $('[name=supplier]').val(),
    }
    // 判断id是否存在
    if (obj.id) { //存在为编辑保存
        putProduct(obj.id, obj).then(res => {
            if (res.code === 1000) {
                location.href = './index.html'
            } else {  //如果保存失败，则弹出失败信息
                alert(code.msg)
            }
        })
    } else {
        postProduct(obj).then(data => {
            if (data.code === 1000) {
                console.log(obj);
                location.href = './index.html'
            } else {
                alert(data.msg)
            }
        })
    }
}

function cancel() {
    location.href = './index.html'
}